import VueRouter from 'vue-router'
import routes from './routes'
import Vue from 'vue';
import store from '@/store'
//安装插件
Vue.use(VueRouter);

let push = VueRouter.prototype.push;
VueRouter.prototype.push = function (location, success, fail) {
    if (success && fail) {

        push.call(this, location, success, fail);
    } else {
        push.call(this, location, () => { }, () => { });
    }

}
let replace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function (location, success, fail) {
    if (success && fail) {

        replace.call(this, location, success, fail);
    } else {
        replace.call(this, location, () => { }, () => { });
    }

}
const router = new VueRouter({
    routes,
    scrollBehavior(to, from, savedPosition) {
        return { x: 0, y: 0 }
    }
})

//没有登录不能访问的页面、
let notVisitArr = ['/cart','/center']

router.beforeEach(async (to, from, next) => {
    // ...
    let hasToken = store.state.user.token;
    let hasUsername = store.state.user.username;
    //     console.log(store.state);
    // console.log(hasUsername);
    if (hasToken) {
        if (to.path == '/login') {
            next('/home');
        } else {
            if (hasUsername) {
                next()
            } else {
                try {
                    await store.dispatch('getUserName')
                    next()
                } catch (error) {
                    await store.dispatch('logout')
                    next('/login')
                }
            }
        }
    } else {
        if (notVisitArr.indexOf(to.path) != -1) {
            next('/login?redirect=' + to.path)
        } else {

            next()
        }
    }
})

export default router